package com.gxuwz.attend.web.servlet.admin;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.gxuwz.attend.context.AppContext;
import com.gxuwz.attend.entity.Admin;
import com.gxuwz.attend.service.admin.AdminService;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;

@WebServlet("/admin/settings")
public class AdminServlet extends HttpServlet {
    private AdminService adminService;
    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void init() throws ServletException {
        super.init();
         adminService = AppContext.getBean(AdminService.class);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        Admin admin = (Admin) session.getAttribute("currentUser");

        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        ObjectMapper objectMapper = new ObjectMapper(); // 确保导入了 Jackson 库
        String json = objectMapper.writeValueAsString(admin);
        response.getWriter().write(json);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        Admin admin1 = (Admin) session.getAttribute("currentUser");

        Admin admin = objectMapper.readValue(request.getInputStream(), Admin.class);
         //对密码进行加密
       /* String encryptedPassword = MD5Util.encryptMd5(admin.getPassword());
        admin.setPassword(encryptedPassword);
     */
        admin.setUserid(admin1.getUserid());
        System.out.println(admin);
        boolean rs = adminService.updateAdminInfo(admin);
        if (rs) {
            // 删除会话信息并返回成功响应
            session.invalidate();
            response.setStatus(HttpServletResponse.SC_OK);  // 设置状态码为200
            response.getWriter().write("{\"message\": \"保存成功\"}");  // 返回成功信息
        } else {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);  // 如果更新失败，返回500错误
            response.getWriter().write("{\"message\": \"保存失败\"}");
        }

    }

}


